/*
 * @Author: Kevin Zhao
 * @Date: 2022-11-06 20:09:12
 * @LastEditTime: 2022-11-06 22:09:11
 * @LastEditors: Kevin Zhao
 * @Description: 
 * @FilePath: \tf-admin\src\utils\exports.ts
 */

import axios, { Method } from "axios";

const service = axios.create({
    baseURL: `${import.meta.env.VITE_APP_HTTPURL}`,
    headers: {
        'content-type': 'application/json',
    },
    responseType: "blob",
    timeout: 60000 // 请求超时时间
});

// 返参接口
interface ParameterInterface {
    status: number // 业务状态码
    desc?: string // 业务状态描述
    data: any // 返参数据
}

// 文件流转blob对象下载
function downloadFile(data) {
    let blob = new Blob([data], { type: `application/octet-stream;charset=utf-8` });
    // 获取heads中的filename文件名
    let downloadElement = document.createElement('a');
    // 创建下载的链接
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    // 下载后文件名
    downloadElement.download = '12345热线.xls';
    document.body.appendChild(downloadElement);
    // 点击下载
    downloadElement.click();
    // 下载完成移除元素
    document.body.removeChild(downloadElement);
    // 释放掉blob对象
    window.URL.revokeObjectURL(href);
}

/**
 * @description: 请求接口
 * @param {string} url
 * @param {Method} method
 * @param {object} data
 * @return {*}
 */
const exports = (url: string, method: Method, data?: object, noToken?: boolean): Promise<ParameterInterface> => {
    return new Promise((resolve, reject) => {
        let params = null
        if (method === 'get' ||
            method === 'GET' ||
            method === 'delete' ||
            method === 'DELETE'
        ) {
            params = data
        }
        let options = {
            method,
            url,
            params,
            data,
        }
        if (!noToken) {
            options.headers = {
                Authorization: (localStorage.getItem("tf_admin_token") as string)
            }
        }
        service(options).then(res => {
            downloadFile(res.data)
            resolve(res)
        })
            .catch(err => {
                reject(err)
            })
    })
}

export default exports;